package rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //建立连接，声明channel和队列
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("8.134.130.95");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("bite");
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("hello",true,false,false,null);
        //接收并消费消息---basicConsume方法
        /**
         * basicConsume
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * queue：队列名称
         * autoAck：是否自动确认，消费者收到消息后，自动和MQ确认
         * callback：回调对象
         */

        //回调对象
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery
                    (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息："+new String(body));
            }
        };
        channel.basicConsume("hello",true,consumer);
        Thread.sleep(2000);
        channel.close();
        connection.close();
    }

}
